package cn.blnp.net.flowable.config;

import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType;
import org.flowable.common.engine.api.delegate.event.FlowableEventDispatcher;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.common.engine.impl.event.FlowableEventDispatcherImpl;
import org.flowable.engine.impl.cfg.StandaloneProcessEngineConfiguration;
import org.flowable.spring.SpringProcessEngineConfiguration;
import org.flowable.spring.boot.EngineConfigurationConfigurer;
import org.flowable.spring.boot.ProcessEngineConfigurationConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <h3>Flowable相关配置</h3>
 *
 * @author <a href="mailto:blnp.yibin@qq.com">lyb</a>
 * @version 1.0
 * @since 2025/5/15 11:48
 */
@Slf4j
@Configuration
public class FlowableConfig implements EngineConfigurationConfigurer<SpringProcessEngineConfiguration> {

    @Override
    public void configure(SpringProcessEngineConfiguration config) {
        FlowableEventDispatcherImpl  flowableEventDispatcher = new FlowableEventDispatcherImpl();
        FlowableEventDispatcher eventDispatcher = config.getEventDispatcher();
        //确保事件分发器已完成初始化
        if (eventDispatcher == null) {
            config.setEventDispatcher(flowableEventDispatcher);
        }
        /**
         *  当前配置仅用于案例测试，如需执行其它测试，请取消注释
         **/
        //指定监听事件类型配置
        //config.getEventDispatcher()
        //        .addEventListener(new GlobalEventListener(),
        //                FlowableEngineEventType.TASK_CREATED,
        //                FlowableEngineEventType.PROCESS_COMPLETED,
        //                FlowableEngineEventType.ENGINE_CREATED,
        //                FlowableEngineEventType.ENGINE_CLOSED
        //        );

        //开启数据库事件日志
        config.setEnableDatabaseEventLogging(true);
        //注册全局日志监听器
        config.getEventDispatcher()
                .addEventListener(
                    new FlowableLoggingListener(),
                    FlowableEngineEventType.TASK_CREATED,
                    FlowableEngineEventType.PROCESS_STARTED,
                    FlowableEngineEventType.PROCESS_COMPLETED,
                    FlowableEngineEventType.ACTIVITY_STARTED
                );
    }
}
